package io.renren.common.utils;

import com.emc.ecs.nfsclient.nfs.io.Nfs3File;
import com.emc.ecs.nfsclient.nfs.io.NfsFileInputStream;
import com.emc.ecs.nfsclient.nfs.io.NfsFileOutputStream;
import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3;
import com.emc.ecs.nfsclient.rpc.CredentialUnix;
import io.renren.common.config.NfsConfig;
import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import lombok.var;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @描述 NFS工具类
 */
public class NfsUtil {
    private static String NFS_IP = NfsConfig.getIp();
    private static String NFS_DIR = NfsConfig.getDir();
    private static String NFS_SUB_DIR = NfsConfig.getSubDir();

    static Nfs3 client;

    static {
        try {
            client = new Nfs3(NFS_IP, NFS_DIR, new CredentialUnix(), 3);
        } catch (Exception e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
    }

    private static Nfs3File getFile(String path) {
        try {
            if (!path.startsWith("/")) {
                path = "/" + path;//无论NFS_DIR末尾带不带/,这里开头必须/,否者堆栈溢出
            }
            return client.newFile(path);
        } catch (Exception e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
    }

    private static List<Nfs3File> getRootFiles() throws IOException {
        return getFile("/").listFiles();
    }

    private static InputStream read(Nfs3File file) throws IOException {
        return new NfsFileInputStream(file);
    }

    private static InputStream read(String path) throws IOException {
        return read(getFile(path));
    }

    private static String readText(String path) throws IOException {
        return BinaryUtil.readText(read(path));
    }

    private static void upload(String path, byte[] data) throws IOException {
        var file = getFile(path);
        BinaryUtil.write(new NfsFileOutputStream(file), data);
    }

    private static void upload(String path, InputStream data) throws IOException {
        upload(path, BinaryUtil.getBytes(data));
    }

    private static void upload(String path, String text) throws IOException {
        upload(path, BinaryUtil.getBytes(text));
    }

    public static String uploadFile(String fileName, InputStream data) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //转换
        String time = sdf.format(new Date());

        String filePath = NFS_SUB_DIR + "/" + time + "-" + fileName;
        upload(filePath, data);

        return filePath;
    }
}